import {
  Dialog
} from "vant";

// 修改图片地址为oss地址
export const getOssUrl = (url) => {
  if (url.startsWith('http://api.xiaozhucaishui.com'))
    return url.replace('http://api.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')
  else if (url.startsWith('https://api.xiaozhucaishui.co'))
    return url.replace('https://api.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  else if (url.startsWith('http://dev.xiaozhucaishui.co'))
    return url.replace('http://dev.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')
  else if (url.startsWith('https://dev.xiaozhucaishui.co'))
    return url.replace('https://dev.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  else if (url.startsWith('http://resources.xiaozhucaishui.com'))
    return url.replace('http://resources.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  return url

};

// 参数is=true 直接调用不判断当前滚动位置
export const goTop = (top, is = false) => {
  try {
    let res = document.body.scrollTop || document.documentElement.scrollTop;
    if (res >= 300 || is) { //当大于400px，按钮出现
      document.body.scrollTop = top ? top : 0;
      document.documentElement.scrollTop = top ? top : 0;
    }
  } catch (error) {

  }

}

export const goTopSmooth = (top, is = false) => {
  try {
    document.querySelector("#topNav").scrollIntoView({
      block: "start",
      behavior: "smooth",
    });
  } catch (error) {

  }

}


export const showMessage = function (first_answer) {
  if (first_answer && first_answer.length > 0) {
    let messages = "";
    for (let item of first_answer) {
      let msg = ''
      if (item.message)
        msg = JSON.parse(item.message);
      else
        return ''

      if (msg.extendedData.type == 111)
        messages = messages + "[表情]，";
      else if (msg.extendedData.type == 11)
        messages = messages + "[图片]，";
      else
        messages =
        messages +
        JSON.parse(item.message).message +
        " ";
    }
    return messages;
  } else {
    return "";
  }
}

// 相对路径地址拼接为oss绝对地址
export const getRelativeOss = (url) => {
  if (!url) return
  if (url.startsWith('http://') || url.startsWith('https://'))
    return url
  else
    return 'https://xzcs-video.oss-cn-beijing.aliyuncs.com' + url

};

// 头像地址拼接oss地址
export const getQavatarOss = (url) => {
  if (!url) return
  if (url.startsWith('http://') || url.startsWith('https://'))
    return url
  else
    return 'https://xzcs-video.oss-cn-beijing.aliyuncs.com' + url

};

// 文字高亮 keyword 需要高亮的文字
export const hightLightText = (text, keyword) => {
  if (!text) return
  for (let key of keyword) {
    if (hasSpecialStr(key)) {
      text = text + ''
    } else {
      const reg = new RegExp(key, 'gi') // 动态正则表达式
      text = text.replace(reg, `<em>${key}</em>`) // 使用replace替换
    }
  }
  return text
};

// JS判断字符串是否含有特殊符号，包括英文与中文两种输入模式。
function hasSpecialStr(str) {
  var specialChars = "~·`!！@#$￥%^…&*()（）—-_=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。emEM";
  // var len=specialChars.length;
  // for ( var i = 0; i < len; i++){
  //     if (str.indexOf(specialChars.substring(i,i+1)) != -1){
  //         return true;
  //     }
  // }
  if (specialChars.indexOf(str) != -1) return true
  return false;
}

export const getText = (str, num = 80) => {
  if (!str) {
    return
  }

  let text = str.replace(/<[^<>]+>/g, "")
  text = text.replace(/&nbsp;/gi, " ");
  text = text.replace(/nbsp;/gi, " ");

  if (text.length > num) return text.substring(0, num) + '...'
  return text
}

export const replaceurl = (detail, name) => {
  let i = 1
  var content = detail.replace(/<img[^>]*>/gi, function (match) {
    var match = match.replace(
      /alt=""/g,
      `alt="${name}-${i++}"`
    )
    return match
  })
  return content
}


export const escape2Html = (str) => {
  var arrEntities = {
    'nbsp': ' ',
    'amp': '&',
    'quot': '"'
  };
  return str.replace(/&(nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });
}

export const getTime = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return `${Y}${M}${D}${h}${m}${s}`
}

export const getTime2 = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return `${Y}${M}${D}`
}

export const getTime3 = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return `${Y}${M}${D}`
}

export const IEVersion = () => {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
  var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if (fIEVersion == 7) {
      return 7;
    } else if (fIEVersion == 8) {
      return 8;
    } else if (fIEVersion == 9) {
      return 9;
    } else if (fIEVersion == 10) {
      return 10;
    } else {
      return 6; //IE版本<=7
    }
  } else if (isEdge) {
    return 'edge'; //edge
  } else if (isIE11) {
    return 11; //IE11
  } else {
    return -1; //不是ie浏览器
  }
}

export function getDiffDay(date_1, date_2) {
  // 计算两个日期之间的差值
  let totalDays, diffDate
  let myDate_1 = Date.parse(date_1)
  let myDate_2 = date_2
  // 将两个日期都转换为毫秒格式，然后做差
  diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

  totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
  // console.log(totalDays)

  return totalDays // 相差的天数
}

export function getServiceType(type) {
  switch (type) {
    case 1:
      return "官方服务商";
    case 2:
      return "金牌服务商";
    case 3:
      return "银牌服务商";
    case 4:
      return "铜牌服务商";
    case 5:
      return "一般服务商";
    default:
      break;
  }
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function splitText(text, keywords) {
  const regexp = new RegExp(
    keywords
    .map((keyword) => escapeRegExp(String(keyword).trim()))
    .join("|"),
    "gi"
  );
  return text.replace(/\t/g, "").replace(regexp, "\t$&\t").split(/\t/);
}

export function wrapText(text, keywords) {
  let str = "";

  splitText(text, keywords).map((substr, i) => {
    str += i % 2 === 0 ? substr : `<em>${substr}</em>`;
    return true;
  });
  return str;
}

//去除富文本字符串中的html标签
export function removeHTMLTags(str) {
  var newStr = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
  newStr = newStr.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
  newStr = newStr.replace(/\n[\s| | ]*\r/g, '\n'); //去除多余空行
  newStr = newStr.replace(/&nbsp;/ig, ''); //去掉&nbsp;
  return newStr;
}


/*
 *   arr 需要查的数组对象
 *   path 需要查的值
 *   key 需要查的键名
 */
export function getArr_objKey(arr, path, key) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] == path) {
      return i
    }
  }
  return 0;
}

export function answerFormat(resultList, queryKeywords, retrieveFieldsIndex) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].quizData.answer_content
    let title = resultList[i].quizData.title
    if (retrieveFieldsIndex == 1)
      queryKeywords.forEach(keyword => {
        title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else
      queryKeywords.forEach(keyword => {
        answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    resultList[i].quizData.answer_content = answer
    resultList[i].quizData.title = title
  }
  return resultList
}

export function answerFormat2(resultList, queryKeywords, retrieveFields) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].policyData.info_content
    let title = resultList[i].policyData.title
    let push_number = resultList[i].policyData.push_number
    let push_date = resultList[i].policyData.push_date


    if (retrieveFields == 'push_number')
      queryKeywords.forEach(keyword => {
        push_number = push_number.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'title')
      queryKeywords.forEach(keyword => {
        title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'info_content_text')
      queryKeywords.forEach(keyword => {
        answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'push_date')
      push_date = "<em>" + push_date + '</em>';

    resultList[i].policyData.info_content = answer
    resultList[i].policyData.push_date = push_date
    resultList[i].policyData.title = title
    resultList[i].policyData.push_number = push_number
  }
  return resultList
}

export function answerFormat3(resultList, queryKeywords, retrieveFields) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].policyData.info_content
    let name = resultList[i].policyData.name
    let push_number = resultList[i].policyData.push_number
    let push_date = resultList[i].policyData.push_date

    if (retrieveFields == 'push_number')
      queryKeywords.forEach(keyword => {
        push_number = push_number.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'name')
      queryKeywords.forEach(keyword => {
        name = name.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'info_content_text')
      queryKeywords.forEach(keyword => {
        answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        name = name.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'push_date')
      push_date = "<em>" + push_date + '</em>';

    resultList[i].policyData.info_content = answer
    resultList[i].policyData.name = name
    resultList[i].policyData.push_date = push_date
    resultList[i].policyData.push_number = push_number
  }
  return resultList
}

export function readJsonFileContent(jsonfileUrl) {
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", jsonfileUrl, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        const reader = new FileReader();
        reader.onload = () => {
          var data = JSON.parse(reader.result)
          resolve({
            data: data
          })
        };
        reader.readAsText(this.response, 'utf-8');
      }
    };
    xhr.send();

  })
}

export function getCateListName(id, cateList) {
  for (let items of cateList) {
    for (let item of items.list) {

      if (item.id == id) return item.name
    }
  }
}

export function downLoadAPP(id, cateList) {
  Dialog.confirm({
      title: "提示",
      message: "该功能需要下载APP",
      confirmButtonText: "去下载",
      cancelButtonText: "再看看",
      confirmButtonColor: 'rgb(1, 119, 253)'
    })
    .then(() => {
      window.open('https://xzcs-apk.oss-cn-hangzhou.aliyuncs.com/xiaozhucaishui.apk')
    })
    .catch(() => {
      // on cancel
    });

}
export function downLoadAPP2(id, cateList) {
  window.open('https://xzcs-apk.oss-cn-hangzhou.aliyuncs.com/xiaozhucaishui.apk')
}
